package com.hyl.reflect;



import com.hyl.entity.Student;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;

/**
 * @Description 通过反射操作对象
 * @Author hyl
 * @Date 2023/4/14 10:08
 **/
public class ReflectionOption {

	@Test //获取实例 p14  ==》 操作
	public void getObject(){
		Class tmp3 = null; //通过全限定名，获取类对象
		try {
			tmp3 = Class.forName("com.hyl.entity.Student");

			//无参
//			Student stu = (Student) tmp3.newInstance();
//			System.out.println(stu);

			//有参
			Constructor constructor = tmp3.getDeclaredConstructor(String.class);
			constructor.setAccessible(true);//可访问
			Student stu2 = (Student) constructor.newInstance("张三");
			System.out.println(stu2);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}


	}

	@Test //操作属性 p16 1-5
	public Student useField(ResultSet resultSet){
		Class tmp3 = null;
		Student stu = null;
		try {
			tmp3 = Class.forName("com.hyl.entity.Student");
			//获取属性
			Field field = tmp3.getDeclaredField("name");
			field.setAccessible(true); //可访问
			field.set(tmp3,"张三");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return stu;
	}

	@Test //操作方法 p17
	public void useMethod(){
		Class tmp3 = null; //通过全限定名，获取类对象
		Student stu = null;
		try {
			tmp3 = Class.forName("com.hyl.entity.Student");
			//获取方法
			 Method method =  tmp3.getDeclaredMethod("show");
			 method.setAccessible(true);
			 //调用==》对象名.方法
			method.invoke(stu);

		} catch (ClassNotFoundException | NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

	}
}
